<template>
    <div style="width: 100%;">
        <TitleTips title="计划内容" />
        <CardBox v-for="(item, index) in list" :key="index" :title="item.itemName">
            <el-row v-if="item.budgetContent" :gutter="24" class="budget-info">
                <el-col :span="24" class="budget-info-title">
                    {{ setBudgetTitle(item.budgetContent) }}
                </el-col>
                <el-col v-for="m in budgetMap" :key="m.code" :lg="8" :xl="6" class="budget-info-item">
                    <span class="label">{{ m.name }}：</span>
                    <span class="value">{{ getValue(m.code, item.budgetContent) }}</span>
                </el-col>
            </el-row>
            <el-row v-if="item.planContent && item.planContent.workAmount" :gutter="24" class="budget-info">
                <el-col :span="24" class="budget-info-title">
                    {{ item.planContent.quarter ? `${item.planContent.quarter}季度计划` : `${item.planContent.year}年度计划` }}
                </el-col>
                <el-col :lg="8" :xl="6" class="budget-info-item">
                    <span class="label">计划工程量：</span>
                    <span class="value">{{ item.planContent.workAmount }} {{ item.planContent.arithmeticalUnit }}</span>
                </el-col>
                <el-col :lg="8" :xl="6" class="budget-info-item">
                    <span class="label">计划完成金额：</span>
                    <span class="value">{{ item.planContent.prepareCompletionMoney }} 元</span>
                </el-col>
                <el-col :span="24" class="budget-info-border">
                    <span class="budget-info-border-line" />
                </el-col>
            </el-row>
            <el-form ref="form" :model="item" class="size-auto width-100" :rules="rules" :inline="true" size="medium" label-width="120px">
                <el-row :gutter="24">
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="计划工程量" prop="workAmount">
                            <el-input v-model.trim="item.workAmount" maxlength="15" clearable placeholder="支持小数点后6位" @change="handleComputed(item, index)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="单价" prop="unitPrice">
                            <el-input v-model.trim="item.unitPrice" maxlength="50" show-word-limit clearable placeholder="请输入" @change="handleComputed(item, index)" />
                        </el-form-item>
                    </el-col>
                    <el-col :lg="8" :xl="6">
                        <el-form-item label="计划完成金额" prop="prepareCompletionMoney" :rules="moneyRules(item.budgetContent.budgetMoney)">
                            <el-input v-model.trim="item.prepareCompletionMoney" disabled maxlength="15" clearable placeholder="支持小数点后6位">
                                <i slot="suffix" class="el-input__icon input-unit">元</i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="工作内容及标准">
                            <el-input v-model.trim="item.content" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model.trim="item.remark" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </CardBox>
    </div>
</template>

<script>
import BigNumber from 'bignumber.js'
import { isNumber6 } from '@/utils/validate'
import { MaintenanceProjectConfigModel, BudgetingOldModel, RoadPlanModel } from '@/models' 

export default {
    name: 'FormCard',
    props: {
        form: {
            type: Array,
            default: () => ([])
        },
        type: {
            type: String,
            default: 'add'
        },
        query: {
            type: Object,
            default: () => ({})
        },
        loading: {
            type: Boolean,
            default: true
        },
        planType: {
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            list: [],
            rules: {
                workAmount: [{ validator: this.validNum, trigger: 'blur' }],
                unitPrice: [{ validator: this.validNum, trigger: 'blur' }],
                adjustmentFactor: [{ validator: this.validNum, trigger: 'blur' }]
            },
            model: new MaintenanceProjectConfigModel(),
            budgetingModel: new BudgetingOldModel(),
            roadPlanModel: new RoadPlanModel(),
            projectList: [],
            budgetContent: [],
            planContent: [],
            budgetMap: [
                { code: 'workAmount', name: '工程量' },
                { code: 'basicFee', name: '基本费用' },
                { code: 'adjustmentFactor', name: '调整系数' },
                { code: 'budgetMoney', name: '预算金额' }
            ],
            budgetMoneys: 0,
            isError: []
        }
    },
    watch: {
        form: {
            handler(newVal) {
                if (newVal.length > 0) {
                    Promise.all([this.getbudgetContent(), this.getPlanContent()]).then(() => {
                        this.list = newVal.map(item => {
                            let budgetContent = {}
                            this.budgetContent.some(m => {
                                if (m.itemId === item.itemId) {
                                    budgetContent = m
                                    return true
                                }
                            })

                            let planContent = {}
                            if (this.planType === 2 || this.planType === 3) {
                                this.planContent.some(m => {
                                    if (m.itemId === item.itemId) {
                                        planContent = m
                                        return true
                                    }
                                })
                            }

                            return {
                                budgetContent,
                                planContent,
                                ...item
                            }
                        }).filter(item => item.budgetContent.workAmount)
                        // 让父组件的加载动画关闭
                        this.$emit('update:loading', false)
                    })
                }
            },
            // immediate: true,
            deep: true
        }
    },
    created() {
        if (this.type === 'add') {
            this.init()
        }
    },
    methods: {
        init() {
            const template = {
                workAmount: null,
                unitPrice: null,
                prepareCompletionMoney: null,
                remark: null
            }
            let callback = {}
            if (this.planType === 2 || this.planType === 3) {
                callback = new Promise(resolve => {
                    Promise.all([this.getbudgetContent(), this.getPlanContent()]).then(() => {
                        resolve()
                    })
                })
            } else if (this.planType === 1) {
                callback = this.getbudgetContent()
            }
            
            callback.then(() => {
                this.list = this.budgetContent.map(item => {
                    let planContent = {}
                    if (this.planType === 2 || this.planType === 3) {
                        this.planContent.some(m => {
                            if (m.itemId === item.itemId) {
                                planContent = m
                                return true
                            }
                        })
                    }   
                    
                    return {
                        budgetContent: item,
                        levelId: item.levelId,
                        levelName: item.levelName,
                        itemId: item.itemId,
                        itemName: item.itemName,
                        content: item.content,
                        arithmeticalUnit: item.arithmeticalUnit,
                        planContent,
                        ...template
                    }
                }).filter(item => item.budgetContent.workAmount) // 把没预算的空过滤掉
                
                // 让父组件的加载动画关闭
                this.$emit('update:loading', false)
            })
        },
        // 设置预算内容标题
        setBudgetTitle(item) {
            let title = ''
            if (item.month) {
                title = item.month + '月份预算'
            } else if (item.quarter) {
                title = item.quarter + '季度预算'
            } else if (item.year) {
                title = '年度预算'
            }
            return title
        },
        getValue(code, item) {
            let res = item[code]
            switch (code) {
                case 'workAmount':
                    res += ' ' + item.arithmeticalUnit
                    break
                case 'budgetMoney':
                    res += ' 元'
                    break
            }
            return res
        },
        getbudgetContent() {
            return this.budgetingModel.getbudgetContent(this.query).then(res => {
                this.budgetContent = res
            })
        },
        getPlanContent() {
            let data = {}
            if (this.planType === 2) {
                data = {
                    roadCode: this.query.roadCode,
                    year: this.query.year
                }
            } else if (this.planType === 3) {
                data = {
                    roadCode: this.query.roadCode,
                    year: this.query.year,
                    quarter: this.query.quarter
                }
            }
            console.log(this.query.roadCode)
            return this.roadPlanModel.getPlanContent(data).then(res => {
                this.planContent = res
            })
        },
        // 针对新建年度养护预算做的计算金额
        handleComputed(item, index) {
            const a = item['workAmount']
            const b = item['unitPrice']
            // 如果2个值任意一个没有则不处理
            if (!a || !b) { return }
            const value = Number(new BigNumber(a).times(b).toFixed(6))
            // 更新计划完成金额
            this.$set(item, 'prepareCompletionMoney', value || null)
        },
        handleValidate() {
            const list = []
            const validas = []
            this.$refs['form'].forEach((item, index) => {
                list.push(new Promise(resolve => {
                    item.validate(valida => {
                        validas.push(valida)
                        resolve()
                    })
                })
                )
            })
            return Promise.all([...list]).then(() => {
                const res = !validas.some(item => item === false)
                return res
            }).catch(() => {
                return false
            })
        },
        validNum(rule, value, callback) {
            if (value && !isNumber6(value)) {
                callback(new Error('填写格式错误'))
            } else {
                callback()
            }
        },
        moneyRules(budgetMoney) {
            return [{
                validator: (rule, value, callback) => this.validMoney(rule, value, callback, budgetMoney),
                trigger: 'change'
            }]
        },
        validMoney(rule, value, callback, budgetMoney) {
            if (value) {
                if (value > budgetMoney) {
                    callback(new Error('不能大于预算金额'))
                } else {
                    callback()
                }
            } else {
                callback()
            }
        }
    },
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 120px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}

.budget-info {
    .budget-info-border{
        padding: 0 16px;
        margin-bottom: 24px;
        .budget-info-border-line {
            display: block;
            width: 100%;
            height: 1px;
            background-color: #F0F4F7;
        }
    }
    .budget-info-title {
        font-size: 14px;
        font-weight: bold;
        color: #171725;
        margin-bottom: 24px;
    }
    .budget-info-item {
        display: flex;
        margin-bottom: 24px;
        font-size: 14px;
        .label {
            width: 120px;
            padding-right: 16px;
            text-align: right;
            color: #171725;
            flex-shrink: 0;
            font-weight: bold;
        }
        .value {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #44444F;
        }
    }
    
} 
</style>
